package com.jzqf.canvas;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WebHttpRequest {
    private static final String TAG = WebHttpRequest.class.getName();
    private static final int TIME_OUT_DELAY = 20000;

    public static void testHttp() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                getRequest("https://www.wanandroid.com/banner/json");
            }
        }.start();

    }

    public static String getRequest(String urlString) {
        String result = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setConnectTimeout(TIME_OUT_DELAY);
            httpURLConnection.setReadTimeout(TIME_OUT_DELAY);
            httpURLConnection.setDoInput(true);//允许输入流，即允许下载
            httpURLConnection.setUseCaches(false);//不使用缓冲
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                result = convertStreamToJson(httpURLConnection.getInputStream());
            } else {
                result = "{\"ErrorInfo\":\"查询错误！网络连接异常！" + responseCode + "错误 ！\",\"SqlExecute\":\" \"}";
            }
            httpURLConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage();
        }
        Log.i(TAG, "---web get result:" + result);
        return result;
    }

    /**
     * post 请求
     *
     * @param urlString  url 请求地址
     * @param jsonString json字符串
     * @return json 字符串
     * @throws IOException
     */
    public String postRequest(String urlString, String jsonString) throws IOException {
        String result;
        URL url = new URL(urlString);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(TIME_OUT_DELAY);
        httpURLConnection.setReadTimeout(TIME_OUT_DELAY);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);  // 设置是否从httpUrlConnection读入
        httpURLConnection.setUseCaches(false); //设置是否使用缓存，post请求不能使用缓存
        httpURLConnection.setRequestProperty("Accept", "application/json");
        httpURLConnection.setRequestProperty("Content-type", "application/json");
        httpURLConnection.setRequestProperty("Charset", "UTF-8");//设置编码格式
        httpURLConnection.connect();
        if (jsonString.length() > 0) {
            PrintStream printStream = new PrintStream(httpURLConnection.getOutputStream());
            printStream.print(jsonString);
            printStream.flush();
            printStream.close();
        }
        InputStream inputStream = httpURLConnection.getInputStream();
        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode == 200) {
            result = convertStreamToJson(inputStream);
        } else {
            result = "[{\"ErrorInfo\":\"查询错误！网络连接异常！" + responseCode + "错误 ！\",\"SqlExecute\":\" \"}]";
        }
        httpURLConnection.disconnect();
        Log.i(TAG, "---web post result:" + result);
        return result;
    }

    /**
     * 把输入流转为json 字符串
     *
     * @param inputStream InputStream
     * @return string
     */
    private static String convertStreamToJson(InputStream inputStream) throws IOException {
        String jsonString;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        jsonString = new String(outputStream.toByteArray());
        inputStream.close();
        outputStream.close();
        return jsonString;
    }

    /**
     * 从指定URL获取图片
     */
    public static Bitmap getBitmap(String urlString) throws IOException {
        Bitmap bitmap;
        URL bitmapUrl;
        InputStream inputStream;
        bitmapUrl = new URL(urlString);
        HttpURLConnection httpURLConnection = (HttpURLConnection) bitmapUrl.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
        bitmap = BitmapFactory.decodeStream(inputStream);
        inputStream.close();
        return bitmap;
    }

    /**
     * 下载文件
     *
     * @param urlString 文件地址
     * @throws IOException IO异常
     */
    public boolean getRequestFile(String urlString) throws IOException {
        boolean isOk = false;
        String result = null;
        URL url = new URL(urlString);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(TIME_OUT_DELAY);
        httpURLConnection.setReadTimeout(TIME_OUT_DELAY);
        httpURLConnection.setDoInput(true);//允许输入流，即允许下载
        httpURLConnection.setUseCaches(false);//不使用缓冲
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.connect();
        int responseCode = httpURLConnection.getResponseCode();
        InputStream inputStream;
        OutputStream fileOutputStream = null;
        if (responseCode == 200) {
            inputStream = httpURLConnection.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "SN_MOBILE_DELIVERY_DRIVER.apk");
            fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int length;
            int couont = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
                couont += length;
                if (couont == length) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    isOk = true;
                } else {//错误处理
                    result = "未完成下载";
                    isOk = false;
                }
            }
        } else {
            result = "网络请求错误" + responseCode;
        }
        if (fileOutputStream != null) {
            fileOutputStream.flush();
            fileOutputStream.close();
        }
        httpURLConnection.disconnect();
        Log.i("", "---web getFile:" + result);
        return isOk;
    }
}
